package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
@Component
public class ValidateHandler extends AbstractTransHandler {


    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        Long userId = createOrderContext.getUserId();
        if(userId == null || userId < 1){
            throw new ValidateException("用户Id无效！");
        }

        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        if(CollectionUtils.isEmpty(cartProductDtoList)){
            throw new ValidateException(OrderRetCode.REQUISITE_PARAMETER_NOT_EXIST.getCode(),
                    OrderRetCode.REQUISITE_PARAMETER_NOT_EXIST.getMessage());
        }

        for (CartProductDto cartProductDto : cartProductDtoList) {
            Long productNum = cartProductDto.getProductNum();
            Long limitNum = cartProductDto.getLimitNum();
            String productName = cartProductDto.getProductName();
            if(productNum > limitNum){
                throw new ValidateException(productName + "库存不足！");
            }
        }

        BigDecimal total = createOrderContext.getOrderTotal();
        if(total.intValue() < 0){
            throw new ValidateException("无效订单金额！");
        }

        String tel = createOrderContext.getTel();
        String streetName = createOrderContext.getStreetName();
        String userName = createOrderContext.getUserName();
        if(StringUtils.isEmpty(tel) || StringUtils.isEmpty(streetName) || StringUtils.isEmpty(userName)){
            throw new ValidateException(OrderRetCode.REQUISITE_PARAMETER_NOT_EXIST.getCode(),
                    OrderRetCode.REQUISITE_PARAMETER_NOT_EXIST.getMessage());
        }
        return true;
    }
}
